Skip to content

Conversation

@akshayutture-augment
Copy link
Contributor

…are (#76186)

* Plugins: Chore: Renamed instrumentation middleware to metrics middleware

* Removed repeated logger attributes in middleware and contextual logger

* renamed loggerParams to logParams

* PR review suggestion

* Add contextual logger middleware

* Removed unused params from logRequest

* Removed unwanted changes

* Safer FromContext method

* Removed traceID from logParams
@akshayutture-augment
Copy link
Contributor Author

@claude review this PR

1 similar comment
@akshayutture-augment
Copy link
Contributor Author

@claude review this PR

@claude
Copy link

claude bot commented Nov 20, 2025

Claude finished @akshayutture-augment's task —— View job


PR Review Complete ✅

Summary

This PR refactors the plugin middleware architecture by:

  1. Renaming InstrumentationMiddlewareMetricsMiddleware
  2. Extracting contextual logger functionality into a separate ContextualLoggerMiddleware
  3. Updating the logger interface to support context-based logging
  4. Cleaning up duplicate logging attributes

Overall Assessment

✅ LGTM - This is a well-executed refactoring that improves separation of concerns. The changes are logical, consistent, and maintain backward compatibility.


Detailed Review

🎯 Architecture & Design

Strengths:

  • Better separation of concerns: Splitting metrics collection and contextual logging into separate middleware is a solid architectural improvement
  • Middleware ordering: The new ContextualLoggerMiddleware is correctly placed before LoggerMiddleware in the stack (pluginsintegration.go:160), ensuring context is enriched before logging
  • Interface extension: Adding FromContext() to the Logger interface enables proper context-aware logging

Considerations:

  • The contextual logger middleware adds context attributes, but those attributes are now duplicated in multiple middleware layers. This appears intentional based on the commit message "Removed repeated logger attributes", but verify this is working as expected in practice.

📝 Code Quality

pkg/plugins/log/logger.go:48-56

Good: The FromContext() implementation safely handles type assertions:

func (d *grafanaInfraLogWrapper) FromContext(ctx context.Context) Logger {
    concreteInfraLogger, ok := d.l.FromContext(ctx).(*log.ConcreteLogger)
    if !ok {
        return d.New()  // Safe fallback
    }
    return &grafanaInfraLogWrapper{l: concreteInfraLogger}
}

pkg/services/pluginsintegration/clientmiddleware/logger_middleware.go:36-60

Good: Simplified logRequest() method - removed pluginCtx and endpoint parameters since they're now in the context:

  • Removed duplicate attribute logging (pluginId, endpoint, dsName, dsUID, uname)
  • Removed traceID from logParams (comment mentions this was intentional)
  • Now uses m.logger.FromContext(ctx).Info() to leverage contextual attributes

Question: Was the traceID intentionally removed from log output, or should it still be included somewhere? The commit message mentions "Removed traceID from logParams" but doesn't explain why.

pkg/services/pluginsintegration/clientmiddleware/contextual_logger_middleware.go

Good: Clean, focused implementation

  • Properly instruments context for all relevant endpoints (QueryData, CallResource, CheckHealth, CollectMetrics)
  • Correctly passes through SubscribeStream, PublishStream, RunStream without modification
  • The instrumentContext() function is well-structured

Minor observation: The instrumentContext() function is defined at package level (line 27) but could potentially be a method on ContextualLoggerMiddleware for better encapsulation. However, this is fine as-is.

pkg/services/pluginsintegration/clientmiddleware/metrics_middleware.go

Good: Clean rename with appropriate comment updates

  • All references to "instrumentation" changed to "metrics"
  • Removed the instrumentContext() call from instrumentPluginRequest() since it's now handled by the separate middleware
  • Import cleanup: removed unused log import (line 8 removed)

🧪 Testing

metrics_middleware_test.go:21

Good: Test name still mentions "InstrumentationMiddleware" in the function name TestInstrumentationMiddleware but correctly uses newMetricsMiddleware() internally.

Suggestion: Consider renaming the test function to TestMetricsMiddleware for consistency:

-func TestInstrumentationMiddleware(t *testing.T) {
+func TestMetricsMiddleware(t *testing.T) {

Missing test coverage: The new ContextualLoggerMiddleware doesn't have dedicated unit tests. Consider adding tests to verify:

  • Context attributes are correctly added
  • Different plugin context scenarios (with/without datasource, with/without user)
  • Middleware properly chains to next handler

🔍 Potential Issues

Logger interface compatibility

Question: Are there other implementations of the Logger interface beyond grafanaInfraLogWrapper and TestLogger? If so, verify they implement the new FromContext() method.

You can check with:

git grep "var _ Logger = " pkg/

📋 Minor Issues

  1. Inconsistent use of any vs interface{}: The changes consistently use any (Go 1.18+), which is good. Verify the project's minimum Go version supports this.

  2. logger_middleware.go:161: The logger name is still "plugin.instrumentation" - consider updating to "plugin.logger" or similar since "instrumentation" now refers specifically to metrics:

    clientmiddleware.NewLoggerMiddleware(cfg, log.New("plugin.instrumentation")),

✅ Positive Highlights

  1. Consistent renaming: All occurrences of InstrumentationMetrics are handled
  2. Backward compatibility: No breaking changes to public APIs
  3. Code cleanup: Removed duplicate attributes and simplified logic
  4. Type safety: Proper type assertions with fallbacks in FromContext()
  5. Test updates: Tests correctly updated to use new function names

Recommendations

High Priority

None - the PR is ready to merge

Medium Priority

  1. Add unit tests for ContextualLoggerMiddleware
  2. Rename test function TestInstrumentationMiddlewareTestMetricsMiddleware for consistency

Low Priority

  1. Consider renaming logger name from "plugin.instrumentation" to something more descriptive (e.g., "plugin.logger" or "plugin.requests")
  2. Add documentation comment explaining why traceID was removed from logParams if not already documented elsewhere

Checklist

  • ✅ Renaming is complete and consistent
  • ✅ No breaking changes
  • ✅ Code follows Go best practices
  • ✅ Separation of concerns improved
  • ⚠️ Missing unit tests for new middleware (non-blocking)
  • ✅ Existing tests updated appropriately

Verdict: Approved - This is a solid refactoring that improves code organization. The minor suggestions above are optional improvements, not blockers.


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants